package java.Dao.Impl;

import Dao.ArticleDAO;
import entity.Article;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/4/29 23:15
 * @Version 1.0 （版本号）
 */
public class ArticleDAOImpl implements ArticleDAO {
    private final Connection connection;

    public ArticleDAOImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public int createArticle(Article article) throws SQLException {
        String sql = "INSERT INTO articles (knowledge_base_id, title, content, author_id) VALUES (?, ?, ?, ?)";

        try (PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setInt(1, article.getKnowledgeBaseId());
            stmt.setString(2, article.getTitle());
            stmt.setString(3, article.getContent());
            stmt.setInt(4, article.getAuthorId());

            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("创建文章失败，没有行受影响");
            }

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1);
                } else {
                    throw new SQLException("创建文章失败，无法获取ID");
                }
            }
        }
    }

    @Override
    public Article getArticleById(int id) throws SQLException {
        String sql = "SELECT * FROM articles WHERE id = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {

            stmt.setInt(1, id);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapRowToArticle(rs);
                }
                return null;
            }
        }
    }

    @Override
    public List<Article> getArticlesByKnowledgeBase(int knowledgeBaseId) throws SQLException {
        String sql = "SELECT * FROM articles WHERE knowledge_base_id = ? ORDER BY created_at DESC";
        List<Article> articles = new ArrayList<>();

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {

            stmt.setInt(1, knowledgeBaseId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    articles.add(mapRowToArticle(rs));
                }
            }
        }
        return articles;
    }

    @Override
    public boolean updateArticle(Article article) throws SQLException {
        String sql = "UPDATE articles SET title = ?, content = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {

            stmt.setString(1, article.getTitle());
            stmt.setString(2, article.getContent());
            stmt.setInt(3, article.getId());

            return stmt.executeUpdate() > 0;
        }
    }

    @Override
    public boolean deleteArticle(int id) throws SQLException {
        String sql = "DELETE FROM articles WHERE id = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {

            stmt.setInt(1, id);
            return stmt.executeUpdate() > 0;
        }
    }

    @Override
    public boolean exists(int id) throws SQLException {
        String sql = "SELECT 1 FROM articles WHERE id = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {

            stmt.setInt(1, id);

            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next();
            }
        }
    }

    private Article mapRowToArticle(ResultSet rs) throws SQLException {
        Article article = new Article();
        article.setId(rs.getInt("id"));
        article.setKnowledgeBaseId(rs.getInt("knowledge_base_id"));
        article.setTitle(rs.getString("title"));
        article.setContent(rs.getString("content"));
        article.setAuthorId(rs.getInt("author_id"));
        article.setCreatedAt(rs.getDate("created_at"));
        article.setUpdatedAt(rs.getTimestamp("updated_at") != null
                ? rs.getDate("updated_at")
                : null);
        return article;
    }
}